package com.po.view.beans.backing;


import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.FontFactoryImp;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


import com.po.view.beans.pojo.AssetInfo;

import com.po.view.beans.util.ADFUtil;

import com.po.view.beans.util.JSFUtil;
import com.po.view.beans.util.MessageUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.math.BigDecimal;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.el.ExpressionFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import javax.faces.validator.ValidatorException;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCDataControl;
import oracle.adf.model.binding.DCIteratorBinding;

import oracle.adf.view.rich.component.rich.nav.RichCommandButton;

import oracle.binding.BindingContainer;

import oracle.binding.OperationBinding;

import oracle.jbo.Row;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.BlobDomain;
import oracle.jbo.server.ViewObjectImpl;

import org.apache.commons.io.IOUtils;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

import po.PurchaseOrderBPEL;
import po.Purchaseorderbpel_client_ep;

import po.types.HeaderType;
import po.types.POAssetType;
import po.types.PurchaseOrderRequest;
import po.types.PurchaseOrderResponse;

import sun.font.FontFamily;

public class PurchaseOrderBackingBean {
  
    private List<AssetInfo> assetInfo;
    private List<SelectItem> vendorList;
    private List<SelectItem> itemList;
    private List<SelectItem> addressList;
    private List<SelectItem> locationList;
   private List<SelectItem> systemList;
   private String result;
   private String masterLocation;
   private String fileName;
    private int assetCount=0;
    int count;
    private static String RESULT;
  
    
    @WebServiceRef
    Purchaseorderbpel_client_ep pce = new Purchaseorderbpel_client_ep();
    public PurchaseOrderBackingBean() {
        super();
        assetInfo= new ArrayList <AssetInfo>();
        AssetInfo laptop = new AssetInfo();
        assetInfo.add(laptop);
        vendorList= new ArrayList<SelectItem>();
        assetCount++;
        count=1;
    }

    public String soaServicePass() throws ParseException,
                                          DatatypeConfigurationException {
        HeaderType ht = new HeaderType();
        ht.setAPPROVEDBY("Test123");
        ht.setBILLINGADDRESS("Test123");
        ht.setCREATEDBY("Test123");
        Date dob=null;
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        dob=df.parse( "2012-07-11");
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(dob);
        XMLGregorianCalendar xmlDate2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), dob.getHours(),dob.getMinutes(),dob.getSeconds(),DatatypeConstants.FIELD_UNDEFINED, cal.getTimeZone().LONG).normalize();
        ht.setCREATEDDATE(xmlDate2);
        ht.setPURCHASEORDERNUMBER("PO_123");
        ht.setRELEASEDATE(xmlDate2);
        ht.setREQUESTEDDATE(xmlDate2);
        ht.setREQUESTEDTO("test123");
        ht.setSHIPMENTADDRESS("test123");
        ht.setSHIPMENTLOCATION("test123");
        ht.setTERMS("test123");
        BigDecimal valDouble = new BigDecimal(123);
        ht.setTOTALAMOUNT(valDouble);
        ht.setVENDORNAME("VID_001");
        
        POAssetType asset = new POAssetType();
        asset.setAdditionalRequirement("nil");
        asset.setAmount(valDouble);
        asset.setBrand("asus");
        asset.setDisplaySize("Size");
        asset.setHardDisk("HD");
        asset.setItemCategory("Cat");
        asset.setItemModel("Model");
        asset.setItemType("Type");
        asset.setMemory("Mem");
        asset.setProcessor("proce");
        asset.setQuantity(valDouble);
        asset.setRate(valDouble);
        asset.setRemarks("rem");
        PurchaseOrderRequest request = new PurchaseOrderRequest();
        request.setHeader(ht);
        List assetList = new ArrayList<POAssetType>();
        assetList =request.getPurchaseOrderAsset();
        assetList.add(asset);
        PurchaseOrderBPEL  pob =pce.getPurchaseOrderBPEL_pt();
        
        PurchaseOrderResponse response =pob.purchaseOrder(request);
        String result =response.getOutcome();
        System.out.println("---------------------------------------"+result+"---------------------------------------");
        
        return null;
    }

    public void setAssetCount(int assetCount) {
        this.assetCount = assetCount;
    }

    public int getAssetCount() {
        return assetCount;
    }

    public void setassetInfo(List<AssetInfo> assetInfo) {
        this.assetInfo = assetInfo;
    }

    public List<AssetInfo> getassetInfo() {
        return assetInfo;
    }

    public String AddAsset() {
        AssetInfo laptop = new AssetInfo();
        assetInfo.add(laptop);
        assetCount++;
        return null;
    }
    
  


    public String removeAsset() {
        Object uuid =
            ADFUtil.resolveExpression("#{requestScope.pLaptopRemove}");
        if (uuid != null) {
            if (assetCount != 1) {
                for (AssetInfo li : assetInfo) {
                    if (uuid.equals(li.getUuid())) {
                        assetInfo.remove(li);
                        return null;
                    }
                }
            }else{
                MessageUtils.displayMessage(null, "Sorry cannot delete. Atleast one asset needed");
            }
        }
        return null;
    }
    
    


    public void setVendorList(List<SelectItem> vendorList) {
        this.vendorList = vendorList;
    }

    public List<SelectItem> getVendorList() {
        vendorList=new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstVendorVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.executeQuery();
        int i=0;
        if(vo.hasNext()){
            i++;
            Row row = vo.first();
            Object vendorName = row.getAttribute("Vendorname");
            vendorList.add(new SelectItem(i ,vendorName.toString()) );
        }
        while(vo.hasNext()){
            vo.next();
            i++;
            Object vendorName = vo.getCurrentRow().getAttribute("Vendorname");
            vendorList.add(new SelectItem(i ,vendorName.toString()) );
        }
                          
        return vendorList;
    }
    public BindingContainer getBindings()
    {
      return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public void setItemList(List<SelectItem> itemList) {
        this.itemList = itemList;
    }

    public List<SelectItem> getItemList() {
        itemList=new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstItemVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.executeQuery();
        if(vo.hasNext()){
            Row row = vo.first();
            Object itemName = row.getAttribute("Itemtype");
            itemList.add(new SelectItem(Integer.parseInt(row.getAttribute("Itemid").toString()) ,itemName.toString()) );
        }
        while(vo.hasNext()){
            vo.next();
            Object itemName = vo.getCurrentRow().getAttribute("Itemtype");
            itemList.add(new SelectItem(Integer.parseInt(vo.getCurrentRow().getAttribute("Itemid").toString()) ,itemName.toString()) );
        }
                          
        return itemList;
    }

    public void setAddressList(List<SelectItem> addressList) {
        this.addressList = addressList;
    }
    public static DCBindingContainer getBinding() {

            FacesContext fctx = FacesContext.getCurrentInstance();
            ExpressionFactory exp = fctx.getApplication().getExpressionFactory();
            return (DCBindingContainer)exp.createValueExpression(fctx.getELContext(),
                                                                 "#{bindings}",
                                                                 DCBindingContainer.class).getValue(fctx.getELContext());

        }
    public List<SelectItem> getAddressList() {
        addressList=new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstAddressVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.executeQuery();
//        DCBindingContainer bc = getBinding();
//        DCIteratorBinding iteratorBindings =
//                       (DCIteratorBinding)bc.get("OmMstAddressVO1Iterator");
//               ViewObject  vo = iteratorBindings.getViewObject();
        
        if(vo.hasNext()){
            Row row = vo.first();
            Object address = row.getAttribute("Address");
            addressList.add(new SelectItem(Integer.parseInt(row.getAttribute("AId").toString()) ,address.toString()) );
        }
        while(vo.hasNext()){
            vo.next();
            Object address = vo.getCurrentRow().getAttribute("Address");
            addressList.add(new SelectItem(Integer.parseInt(vo.getCurrentRow().getAttribute("AId").toString()) ,address.toString()) );
        }
                          
        return addressList;
    }

    public String saveToPdfAndService() throws IOException, DocumentException,
                                               ParseException,
                                               DatatypeConfigurationException {
         createPdf();
        //newRow("2014-07-07");
       //soaServicePass();
        return null;
    }
    
    //Return address from LOV
    public String returnAddress(String address){
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator1 =
            dcBindings.findIteratorBinding("OmMstAddressVO1Iterator");
        ViewObjectImpl vo1 = (ViewObjectImpl)iterator1.getViewObject();
        vo1.setApplyViewCriteriaName("OmMstAddressVOCriteria");
        vo1.setNamedWhereClauseParam("pAddressId",address);
        vo1.executeQuery();
        String addressValue = vo1.first().getAttribute("Address").toString();
        Object location = vo1.first().getAttribute("Location");
        setMasterLocation(location.toString());
        return addressValue;
    }
    
    public XMLGregorianCalendar returnDate(String dateString) throws ParseException,
                                                    DatatypeConfigurationException {
        Date date=null;
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        date=df.parse( dateString );
        GregorianCalendar cal1 = new GregorianCalendar();
        cal1.setTime(date);
        
        XMLGregorianCalendar xmlDate2 = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH)+1, cal1.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
        return xmlDate2;
    }
    
    public String newRow(String date) {
        DCBindingContainer bindings =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        OperationBinding operationBinding =
            bindings.getOperationBinding("CreateInsert");
        Object result = operationBinding.execute();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmPoNumberVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        Object poNumber = vo.getCurrentRow().getAttribute("PoNumber");
        vo.getCurrentRow().setAttribute("PoDate", date);
        OperationBinding operationBinding1 = bindings.getOperationBinding("Commit");
        operationBinding1.execute();
        if(operationBinding.getErrors().isEmpty()){
            System.out.println("No errors");
        }
        return poNumber.toString();
    }
    
    public void createPdf()
        throws IOException, DocumentException,ParseException,
                                   DatatypeConfigurationException {
        
        //Variable declaration
        boolean isPass = true;

        //Retrieving value from front end
        Object created_By =
            JSFUtil.resolveExpression("#{pageFlowScope.createdBy}");
        Object b_Address =
            JSFUtil.resolveExpression("#{pageFlowScope.b_Address}");
        Object c_Date = JSFUtil.resolveExpression("#{pageFlowScope.c_Date}");
        Object S_location =
            JSFUtil.resolveExpression("#{pageFlowScope.S_location}");
        Object rel_date =
            JSFUtil.resolveExpression("#{pageFlowScope.rel_date}");
        Object v_name = JSFUtil.resolveExpression("#{pageFlowScope.v_name}");
        Object req_To = JSFUtil.resolveExpression("#{pageFlowScope.req_To}");
        Object appr_By = JSFUtil.resolveExpression("#{pageFlowScope.appr_By}");
        Object terms = JSFUtil.resolveExpression("#{pageFlowScope.terms}");
        Object t_amt =JSFUtil.resolveExpression("#{pageFlowScope.t_Amt}").toString();


        //Validation of front end values
        if (created_By == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Created By cannot be null");
            isPass = false;
        }
        if (t_amt == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Total Amount cannot be null");
            isPass = false;
        }
        if (b_Address == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Billing Address cannot be null");
            isPass = false;
        }
        if (c_Date == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Created Date cannot be null");
            isPass = false;
        }
        if (S_location == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Shipment Location cannot be null");
            isPass = false;
        }
        if (rel_date == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Release date cannot be null");
            isPass = false;
        }
        if (v_name == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Vendor name cannot be null");
            isPass = false;
        }
        if (req_To == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Requested to cannot be null");
            isPass = false;
        }
        if (appr_By == null) {
            MessageUtils.displayErrorMessage(null,
                                             "Approved By cannot be null");
            isPass = false;
        }
        if (terms == null) {
            MessageUtils.displayErrorMessage(null, "Terms cannot be null");
            isPass = false;
        }
        int i = 0;


        //validation of pojo class values of front end attributes
        for (AssetInfo li : assetInfo) {
            i++;
            Object category = li.getCategory();
            if (category == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Category cannot be null");
                isPass = false;
            } else if (category.equals("System")) {
                if (li.getMemory() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Memory cannot be null");
                    isPass = false;
                }
                if (li.getSize() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Display Size cannot be null");
                    isPass = false;
                }
                if (li.getProcessor() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Processor cannot be null");
                    isPass = false;
                }
                if (li.getHd() == null) {
                    MessageUtils.displayErrorMessage(null,
                                                     "Hard Disk cannot be null");
                    isPass = false;
                }
            }
            if (li.getModel() == null) {
                MessageUtils.displayErrorMessage(null, "Model cannot be null");
                isPass = false;
            }
            if (li.getBrand() == null) {
                MessageUtils.displayErrorMessage(null, "Brand cannot be null");
                isPass = false;
            }
            if (li.getType() == null) {
                MessageUtils.displayErrorMessage(null, "Type cannot be null");
                isPass = false;
            }
            if (li.getRate() == null) {
                MessageUtils.displayErrorMessage(null, "Rate cannot be null");
                isPass = false;
            }
            if (li.getAdd_req() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Additional requirement cannot be null");
                isPass = false;
            }
            if (li.getQty() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Quantity cannot be null");
                isPass = false;
            }
            if (li.getAmount() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Amount cannot be null");
                isPass = false;
            }
            if (li.getRemark() == null) {
                MessageUtils.displayErrorMessage(null,
                                                 "Remark cannot be null");
                isPass = false;
            }
        }
        if (!isPass) {
            return;
        }


        //Retrieving values by reverse LOV process

        //Vendor name
        int vendor_id = Integer.parseInt(v_name.toString());
        if(vendor_id<10){
            v_name="VID_00"+Integer.valueOf(vendor_id);
        }else if(vendor_id<100){
            v_name="VID_0"+Integer.valueOf(vendor_id);
        }else{
            v_name="VID_"+Integer.valueOf(vendor_id);
        }
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstVendorVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.setApplyViewCriteriaName("OmMstVendorVOCriteria");
        vo.setNamedWhereClauseParam("pVendorId", v_name);
        vo.executeQuery();
        vo.getQuery();
        Object vendor = null;
        Row row = vo.first();
        vendor = row.getAttribute("Vendorname");


        //Address
        String billing_add = returnAddress(b_Address.toString());
        Object s_Address =
            JSFUtil.resolveExpression("#{pageFlowScope.s_Address}");
        String ship_ad = returnAddress(s_Address.toString());
        String mastLocation = getMasterLocation();
    

        // Passing data to service
        HeaderType ht = new HeaderType();
        ht.setAPPROVEDBY(appr_By.toString());
        ht.setBILLINGADDRESS(billing_add.toString());
        ht.setCREATEDBY(created_By.toString());
        
        DateFormat formatter =
            new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
         Date date1 = (Date)formatter.parse(c_Date.toString());
       // DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        //Date date1 = (Date)df.parse(c_Date.toString());
        
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        String formatedDate1 =
            cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) + 1) +
            "-" + cal1.get(Calendar.DATE);
        XMLGregorianCalendar xmlDate = returnDate(formatedDate1);
        System.out.println("XML Date="+xmlDate.toString());
        ht.setCREATEDDATE(xmlDate);
        
        
       // Date date2 = (Date)df.parse(rel_date.toString());
        Date date2 = (Date)formatter.parse(rel_date.toString());
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date2);
        String formatedDate2 =
        cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) + 1) +
        "-" + cal1.get(Calendar.DATE);
        
        
        
         xmlDate = returnDate(formatedDate2);
         
         
            String PONumber =newRow(xmlDate.toString());         
        ht.setPURCHASEORDERNUMBER("PO_"+PONumber);
        String poNumberString = mastLocation+PONumber;
        System.out.println("XML Date="+xmlDate.toString());
        ht.setRELEASEDATE(xmlDate);
        ht.setREQUESTEDTO(req_To.toString());
        ht.setSHIPMENTADDRESS(ship_ad.toString());
        ht.setSHIPMENTLOCATION(S_location.toString());
        ht.setTERMS(terms.toString());
        BigDecimal valDouble = new BigDecimal(Integer.parseInt(t_amt.toString()));
        ht.setTOTALAMOUNT(valDouble);
        ht.setVENDORNAME(v_name.toString());
        POAssetType asset = new POAssetType();
        PurchaseOrderRequest request = new PurchaseOrderRequest();
        request.setHeader(ht);
        List assetList = new ArrayList<POAssetType>();
        assetList =request.getPurchaseOrderAsset();
        for (AssetInfo li : assetInfo) {
            i++;
            asset.setItemCategory(li.getCategory());
            if ((li.getCategory().equals("System"))){
                asset.setItemModel(li.getModel());
                asset.setHardDisk(li.getHd());
                asset.setMemory(li.getMemory());
                asset.setProcessor(li.getProcessor());
                asset.setDisplaySize(li.getSize());
            }
        asset.setAdditionalRequirement(li.getAdd_req());
        valDouble = new BigDecimal(Integer.parseInt(li.getAmount()));
        asset.setAmount(valDouble);
        asset.setBrand(li.getBrand());
        asset.setItemType(li.getType());
        valDouble = new BigDecimal(Integer.parseInt(li.getQty()));
        asset.setQuantity(valDouble);
        valDouble = new BigDecimal(Integer.parseInt(li.getRate()));
        asset.setRate(valDouble);
        asset.setRemarks(li.getRemark());
            assetList.add(asset);
        }
        
       
        PurchaseOrderBPEL  pob =pce.getPurchaseOrderBPEL_pt();
        
        PurchaseOrderResponse response =pob.purchaseOrder(request);
        String result =response.getOutcome();
        System.out.println("---------------------------------------"+result+"---------------------------------------");
        
        
        //Passing data to service complete

        // PDF creation steps
        Document document = new Document();
//        RESULT =
//               "/home/ADF/Purchase Order" + poNumberString.toString() + ".pdf"; //PDF Path------------------------
                RESULT =
              "C:/Purchase Order" + poNumberString.toString() + ".pdf"; //PDF Path------------------------
        setResult(RESULT);
       setFileName("PurchaseOrder"+poNumberString + ".pdf");
        PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
        document.add(new Paragraph("                                                        WORK ORDER",
                                   fontbold));
        document.add(new Paragraph("                                                 _______________"));
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph("                                                                                                                           PO No:"+poNumberString));
       
        Date date = (Date)formatter.parse(rel_date.toString());
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        String formatedDate =
            cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) +
            "/" + cal.get(Calendar.YEAR);
        System.out.println("formatedDate : " + formatedDate);
        document.add(new Paragraph("                                                                                                                           PO Date:" +
                                   formatedDate));
        document.add(new Paragraph("    "));
        document.add(new Paragraph("To"));
        document.add(new Paragraph("    " + vendor.toString()));
        document.add(new Paragraph("    "));
        document.add(new Paragraph("    "));
        document.add(new Paragraph("Dear Sir,"));
        document.add(new Paragraph("We would like to place the order for the following products:"));
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph("                                      "));

        //Call for adding table content
        document.add(createFirstTable(assetInfo));


        document.add(new Paragraph("    "));
        document.add(new Paragraph("    "));
//        document.add(new Paragraph("Billing Address: " + billing_add));
//        document.add(new Paragraph("Delivery Address: " + ship_ad));
        
        PdfPTable table = new PdfPTable(8);
        PdfPCell cell;
        Font heading = FontFactory.getFont("Times-Roman", 12, Font.BOLD,BaseColor.RED);
        cell = new PdfPCell(new Phrase("Billing Address",heading));
        cell.setColspan(4);
        cell.setBorder(0);
      
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Shipping Address",heading));
        cell.setColspan(4);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(billing_add));
        cell.setColspan(4);
        
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(ship_ad));
        cell.setColspan(4);
        cell.setBorder(0);
        table.addCell(cell);
        document.add(table);
        
        
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph("Kindly arrange to deliver the same at the earliest"));
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph("Thanking you,"));
        document.add(new Paragraph("    "));
        document.add(new Paragraph("                                      "));
        document.add(new Paragraph(appr_By.toString()));
        document.close();
        FacesContext context = FacesContext.getCurrentInstance();
                       RichCommandButton button =
                           (RichCommandButton)JSFUtil.findComponent("consolidatedPreview");
                       ExtendedRenderKitService service =
                           Service.getRenderKitService(context,
                                                       ExtendedRenderKitService.class);

                       service.addScript(context,
                                         "var popup = AdfPage.PAGE.findComponent(\"" +
                                         button.getClientId(context) +
                                         "\");AdfActionEvent.queue(popup,true);");
        MessageUtils.displayMessage(null,
                                    "Purchase Order saved successfully");
        
             

    }
    
    public static PdfPTable createFirstTable(List<AssetInfo> assetInfo1) throws DocumentException,
                                                      FileNotFoundException {
        
        PdfPTable table = new PdfPTable(11);
        table.setWidthPercentage(100);
               table.setSpacingBefore(0f);
               table.setSpacingAfter(0f);
        PdfPCell cell;
        cell = new PdfPCell(new Phrase("SL.No"));
        cell.setColspan(1);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Description"));
        cell.setColspan(4);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Quantity"));
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Rate"));
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Total Amount"));
        cell.setColspan(2);
        table.addCell(cell);
        int i=0;
        for (AssetInfo li : assetInfo1) {
            i++;
              cell = new PdfPCell(new Phrase(Integer.toString(i)));
              cell.setColspan(1);
              table.addCell(cell);
              cell = new PdfPCell(new Phrase(li.getBrand()+" "+li.getType()+" "+ li.getModel()));
              cell.setColspan(4);
              table.addCell(cell);
              cell = new PdfPCell(new Phrase(li.getQty()));
              cell.setColspan(2);
              table.addCell(cell);
              cell = new PdfPCell(new Phrase( li.getRate()));
              cell.setColspan(2);
              table.addCell(cell);
              cell = new PdfPCell(new Phrase("Rs. "+li.getAmount()+" /-"));
              cell.setColspan(2);
              table.addCell(cell);
          }
        
        cell = new PdfPCell(new Phrase("                                                                        Total"));
        cell.setColspan(9);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Rs. "+JSFUtil.resolveExpression("#{pageFlowScope.t_Amt}").toString()+" /-"));
        cell.setColspan(2);
        table.addCell(cell);
        return table;
    }


    public void setLocationList(List<SelectItem> locationList) {
        this.locationList = locationList;
    }

    public List<SelectItem> getLocationList() {
        locationList=new ArrayList<SelectItem>();
        DCBindingContainer dcBindings = (DCBindingContainer)getBindings();
        DCIteratorBinding iterator =
            dcBindings.findIteratorBinding("OmMstLocationVO1Iterator");
        ViewObjectImpl vo = (ViewObjectImpl)iterator.getViewObject();
        vo.executeQuery();
        if(vo.hasNext()){
            Row row = vo.first();
            Object loc = row.getAttribute("Locationname");
            locationList.add(new SelectItem(Integer.parseInt(row.getAttribute("Locationid").toString()) ,loc.toString()) );
        }
        while(vo.hasNext()){
            vo.next();
            Object address = vo.getCurrentRow().getAttribute("Locationname");
            locationList.add(new SelectItem(Integer.parseInt(vo.getCurrentRow().getAttribute("Locationid").toString()) ,address.toString()) );
        }
                          
        return locationList;
    }

   

    public void setSystemList(List<SelectItem> systemList) {
        this.systemList = systemList;
    }

    public List<SelectItem> getSystemList() {
        systemList= new ArrayList<SelectItem>();
        Object cat =JSFUtil.resolveExpression("#{item.category}");
        if(cat!=null){
            if(cat.toString().equals("System")){
                systemList.add(new SelectItem(1,"System"));
                systemList.add(new SelectItem(2,"Laptop"));
            }else{
                systemList.add(new SelectItem(1,"Keyboard"));
                systemList.add(new SelectItem(2,"Mouse"));
            }
        }
       
        return systemList;
    }



    public void downloadFile(FacesContext facesContext,
                             java.io.OutputStream outputStream) throws IOException,
                                                                       DocumentException,
                                                                       ParseException {
        // Add event code here...
        if(count==2){
          //  createPdf();
            File file = new File(RESULT);
            FileInputStream fis = new FileInputStream(file);
            IOUtils.copy(fis, outputStream);
            fis.close();
            outputStream.flush();
         count++;
        }
        
    }


    public void setResult(String result) {
        this.result = result;
    }

    public String getResult() {
        return result;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() throws IOException, DocumentException,
                                       ParseException {
      
        if(count==1){
           
            count++;
        }
        
        return fileName;
    }

    public void setMasterLocation(String masterLocation) {
        this.masterLocation = masterLocation;
    }

    public String getMasterLocation() {
        return masterLocation;
    }

    public void numberValidator(FacesContext facesContext,
                                UIComponent uIComponent, Object object) {
        if (object != null) {
           String name = object.toString();
           String expression = "^[0-9]*";
           CharSequence inputStr = name;
           Pattern pattern = Pattern.compile(expression);
           Matcher matcher = pattern.matcher(inputStr);
           String msg = "Please enter numeric value";
           if (matcher.matches()) {

           } else {
             throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                           msg, null));
           }
         }
    }
}
